<template>
    <el-dialog v-model="dialogState" width="830" :show-close="false" @closed="handleClose" :z-index="9">
        <template #header>
            <div class="dialog-header">
                <h4>选择员工</h4>
                <div class="tip">
                    <el-icon :size="18">
                        <Warning />
                    </el-icon>
                    <span>若是员工账号不可用，则无法选择</span>
                </div>
                <div class="close">
                    <el-icon style="cursor: pointer;" @click="dialogState = false">
                        <Close />
                    </el-icon>
                </div>
            </div>
        </template>
        <div class="dialog-content">
            <div class="left">
                <span>部门</span>
                <Department @tree-check="handleTreeCheck" />
            </div>
            <div class="right">
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item prop="job_status" style="margin-right: 10px;">
                        <el-select v-model="queryParams.job_status" placeholder="请选择" style="width: 180px">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :disabled="item.disabled" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="keywords" style="margin-right: 10px;">
                        <el-input v-model="queryParams.keywords" placeholder="请输入员工姓名" clearable style="width: 250px" />
                    </el-form-item>
                    <el-form-item style="margin-right: 0;">
                        <el-button type="primary" @click="handleQuery">搜索</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="list">
                    <el-table-column prop="name" width="60">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.checked" @change="handleCheck(scope.row)"></el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="120" />
                    <el-table-column prop="mobile" label="手机号" />
                    <el-table-column prop="job_status" label="实名状态" width="120">
                        <template #default="scope">
                            <el-tag v-if="scope.row.is_real === 1">已实名</el-tag>
                            <el-tag v-else type="warning">未实名</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="job_status" label="状态" width="80">
                        <template #default="scope">
                            <el-tag v-if="scope.row.job_status === 1" type="warning">试用</el-tag>
                            <el-tag v-if="scope.row.job_status === 2">正式</el-tag>
                            <el-tag v-if="scope.row.job_status === 3" type="warning">待离职</el-tag>
                            <el-tag v-if="scope.row.job_status === 4" type="danger">已离职</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
                <Pagination :total="total" :current-page="pageInfo.page" :page-size="pageInfo.limit"
                    @pagination-change="handlePaginationChange" />
                <div class="next"><el-button type="primary" @click="submit">下一步</el-button></div>
            </div>
        </div>
    </el-dialog>
</template>
<script lang="ts" setup>
import { user_list } from '@/api/cf'
import Pagination from '@/components/Pagination.vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import Department from './Department.vue'


interface Tree {
    id: number;
    name: string;
    children?: Tree[];
}
interface User {
    id: number;
    name: string;
    mobile: string;
    job_status: number;
    is_real: number;
    checked: boolean;
    user_id: number;
}

const props = defineProps({
    modelValue: Boolean
})

const list = ref<User[]>([])
const queryParams = reactive({
    job_status: 2,
    keywords: '',
    dept_id: null,
    is_enable: 1
})
const total = ref(0)
const pageInfo = reactive({
    page: 1,
    limit: 10
})
const options = [
    {
        value: 2,
        label: '正式',
    },
    {
        value: 1,
        label: '试用',
        disabled: true
    }
]
const userSelectedId = ref(0)

const emit = defineEmits(['update:modelValue', 'submit-user-id', 'submit-id'])

// 核心：使用计算属性替代watch
const dialogState = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

watch(
  () => dialogState.value,
  val => {
    if(!val) {
      list.value.forEach((item: any) => {
        item.checked = false
      })
    }
  }
)

const handleClose = () => {
    // 关闭时的清理操作
}

const handlePaginationChange = ({ page, size }: { page: number; size: number }) => {
    pageInfo.page = page
    pageInfo.limit = size
    list.value = []
    getUserList()
}

const getUserList = async () => {
    await user_list({
        ...queryParams,
        ...pageInfo
    }).then(res => {
        let data = res.data as User[]
        data.forEach((item: any) => {
            item.checked = false
        })
        list.value = data
        total.value = res.count
    })
}

const handleCheck = (row: any) => {
    list.value.forEach((item: any) => {
        if (item.id !== row.id) {
            item.checked = false
        }
    })
}

const handleTreeCheck = (selectedDepartmentsIds: any) => {
    queryParams.dept_id = selectedDepartmentsIds.join(',')
    handleQuery()
}

const handleQuery = () => {
    pageInfo.page = 1
    getUserList()
}

const submit = () => {
    const selected = list.value.find((u: User) => u.checked)
    if (!selected) {
        ElMessage.error({
            message: '请选择员工'
        })
        return
    }

    userSelectedId.value = selected.user_id
    dialogState.value = false
    emit('submit-user-id', userSelectedId.value)
    emit('submit-id', selected.id )

   const selectedItem = list.value.find(item => item.checked);
    if (selectedItem) {
        emit('submit-item', selectedItem);
    }
}

onMounted(async () => {
    await getUserList()
})

</script>
<style scoped lang="scss">
.dialog-header {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: solid 1px #eee;

    h4 {
        font-size: 18px;
        color: #333;
        font-weight: normal;
    }

    .tip {
        font-size: 16px;
        color: #999;
        background-color: #f3f8fb;
        display: flex;
        align-items: center;
        padding: 3px 5px;
        border-radius: 5px;
        margin-left: 10px;

        span {
            margin-left: 5px;
        }
    }

    .close {
        flex: 1;
        display: flex;
        justify-content: flex-end;
    }
}

.dialog-content {
    display: flex;

    .left {
        width: 230px;
        border: solid 1px #eee;
        padding: 15px;

        span {
            font-size: 14px;
            font-weight: normal;
            color: #333;
            display: block;
            margin-bottom: 10px;
        }
    }

    .right {
        flex: 1;
        margin-left: 15px;
    }

    .next {
        display: flex;
        justify-content: flex-end;
    }
}
</style>